package cn.hjh.rpc.register;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

import cn.hjh.rpc.define.RPCClientBean;


/**
 * RPC服务定义的初始化配置（包括服务端和客户端）
 * @author jianhua.huang
 */
@Component
public class RPCBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	private Logger logger = LoggerFactory.getLogger(getClass());

	protected BeanDefinitionRegistry beanRegistry;

	@Override
	public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException 
	{
		if(null != beanFactory) {//sonar 修改
			// RPCClientBean的处理
			processClientBean(beanFactory);
		}
	}


	/**
	 * @param beanFactory
	 * @param rpcProperties
	 */
	private void processClientBean(ConfigurableListableBeanFactory beanFactory) 
	{
		// 客户端调用类注册开始
		Map<String, RPCClientBean> beans = beanFactory.getBeansOfType(RPCClientBean.class);
		RPCClientBeanRegister register = beanFactory.getBean(RPCClientBeanRegister.class);
		for (RPCClientBean bean : beans.values()) 
		{
			logger.debug("为该客户端调用类找到支持的注册器，开始注册...");
			register.register(bean, beanFactory, beanRegistry);
			logger.debug("客户端调用类{}注册成功.");
		}
	}


	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		this.beanRegistry = registry;
	}
}